package cn.shop.gateway;

import cn.hutool.db.Entity;
import cn.shop.gateway.db.DbUtil;
import cn.shop.gateway.http.ApiUtil;
import cn.shop.gateway.http.WebServer;
import cn.shop.gateway.model.MerchantGamePartition;
import cn.shop.gateway.utils.PaneUtil;
import cn.shop.gateway.utils.WatchUtil;
import cn.shop.gateway.view.LoginController;
import cn.shop.gateway.view.RootLayoutController;
import cn.shop.gateway.view.SelectTemplateController;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Modality;
import javafx.stage.Stage;

import java.io.IOException;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

import static cn.shop.gateway.utils.Context.orderSellFilePath;

/**
 * @author : 李一涵
 * @date : Created in 2021-12-7 14:59
 * @description :
 */
public class MainApp extends Application {

    public static ConcurrentHashMap<String, RootLayoutController> stages = new ConcurrentHashMap<>(2);

    private Stage primaryStage;

    public static void main(String[] args) throws Exception {
        Config.init();
        DbUtil.init();
        ApiUtil.init(Config.getString("api.url"), Config.getInt("api.port"));
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        this.primaryStage = primaryStage;
        this.primaryStage.setTitle("交易平台网关");
        this.primaryStage.getIcons().add(new Image("image/icon.jpg"));
        //initRootLayout();
        Optional<Long> id = DbUtil.getMerchantInfo();
        //没有登录
        if (!id.isPresent() || id.get() == 0) {
            showLoginDialog();
        } else {
            Optional<Long> templateId = DbUtil.getGameTemplate();
            // 没有选模板
            if (!templateId.isPresent() || templateId.get() == 0) {
                showSelectTemplate(id.get());
            } else {
                initRootLayout();
            }
        }
    }

    public void initRootLayout() throws Exception {
        FXMLLoader load = PaneUtil.loadPane("view/RootLayout.fxml");
        AnchorPane rootLayout = load.load();
        Scene scene = new Scene(rootLayout);
        primaryStage.setScene(scene);
        primaryStage.setOnCloseRequest(event -> {
            RootLayoutController controller = MainApp.stages.get("main");
            if (controller != null) {
                DbUtil.updateSendCount(controller.getAllCount(), controller.getSuccessCount(), controller.getFailCount());
            }
            System.exit(0);
        });
        primaryStage.show();
        RootLayoutController controller = load.getController();
        MainApp.stages.put("main", controller);
        WebServer.start();
        Entity entity = DbUtil.getSendCount();
        if (entity != null) {
            controller.setAllCount(entity.getLong("allCount"));
            controller.setSuccessCount(entity.getLong("successCount"));
            controller.setFailCount(entity.getLong("failCount"));
        }
        controller.setPort(Config.getString("server.port"));
        List<Entity> list = DbUtil.getGamePartitions();
        for (Entity e : list) {
            WatchUtil.watch(orderSellFilePath(e.getStr(MerchantGamePartition.Field.FOLDER)));
        }
    }

    public void showLoginDialog() throws IOException {
        FXMLLoader loader = PaneUtil.loadPane("view/Login.fxml");
        AnchorPane loginPane = loader.load();
        Stage loginStage = new Stage();
        loginStage.setTitle("登录");
        loginStage.initModality(Modality.WINDOW_MODAL);
        loginStage.initOwner(primaryStage);
        loginStage.setOnCloseRequest(event -> System.exit(0));
        Scene scene = new Scene(loginPane);
        loginStage.setScene(scene);
        LoginController loginController = loader.getController();
        loginController.setLoginStage(loginStage);
        loginController.setApp(this);
        loginStage.show();
    }

    public void showSelectTemplate(long id) throws IOException {
        SelectTemplateController controller = new SelectTemplateController();
        controller.setId(id);
        FXMLLoader loader = PaneUtil.loadPane("view/SelectTemplateDialog.fxml");
        loader.setController(controller);
        AnchorPane selectPane = loader.load();
        Stage dialogStage = new Stage();
        dialogStage.setTitle("选择模板");
        dialogStage.initModality(Modality.WINDOW_MODAL);
        dialogStage.initOwner(primaryStage);
        dialogStage.setOnCloseRequest(event -> System.exit(0));
        Scene scene = new Scene(selectPane);
        dialogStage.setScene(scene);
        controller.setDialogStage(dialogStage);
        controller.setApp(this);
        dialogStage.show();
    }
}
